<template>
  <div>
    <el-dialog
      :title="formData.policyId?'编辑策略':'新增策略'"
      :visible="showDialog"
      width="600px"
      @close="closeDialog"
    >
      <el-form ref="policyForm" label-width="120px" :model="formData" :rules="rules">
        <!-- 策略名称 -->
        <el-form-item label="策略名称" prop="policyName">
          <el-input v-model="formData.policyName" placeholder="请输入" maxlength="15" show-word-limit style="width: 84%;" />
        </el-form-item>
        <!-- 策略名称 -->
        <el-form-item label="策略方案" prop="discount">
          <el-input-number v-model="formData.discount" placeholder="请输入" style="width: 84%;" controls-position="right" :min="1" :max="100" />
        </el-form-item>
        <el-row class="TwoButton">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submitOK">确 定</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addNewPoliceAPI, policyDetailAPI, editPoliceAPI } from '@/api/policy'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      formData: {
        policyName: '',
        discount: undefined
      },
      // 定义校验规则
      rules: {
        policyName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        discount: [{ required: true, message: '最少为1', trigger: 'change' }]
      }
    }
  },

  methods: {
  // 关闭弹窗
    closeDialog() {
      // 数据重置
      this.formData = {
        policyName: '',
        discount: undefined
        // 关闭弹窗
      }
      this.$emit('closeDialog')
      // 重置表单项目的值，防止在表单提交时发生值覆盖。
      this.$refs.policyForm.resetFields()
    },
    // 点击确定按钮
    async  submitOK() {
      let mes = ''
      try {
        await this.$refs.policyForm.validate()
        if (this.formData.policyId) {
          await editPoliceAPI(this.formData)
          mes = '编辑成功'
        } else {
          await addNewPoliceAPI(this.formData)
          mes = '新增成功'
        }
        this.$message.success(mes)
        this.$emit('closeDialog')
        this.$emit('getPolicyList')
      } catch (error) {
        this.$message.error('添加失败，请重试')
        console.log(error)
      }
    },
    // 父组件调用这个方法进行数据回显
    async  policyDetail(id) {
      const res = await policyDetailAPI(id)
      this.formData = res.data
    }
  }
}
</script>

<style lang="scss" scoped>
 .TwoButton {
    text-align: center;
  }
</style>
